package com.yanfan.zutai.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yanfan.common.annotation.Log;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.page.TableDataInfo;
import com.yanfan.common.core.text.Convert;
import com.yanfan.common.enums.BusinessType;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.common.utils.poi.ExcelUtil;
import com.yanfan.zutai.aop.SysInitData;
import com.yanfan.zutai.aop.SysInitUpdateData;
import com.yanfan.zutai.aop.SysQueryData;
import com.yanfan.zutai.domain.BWeiXin;
import com.yanfan.zutai.service.IBWeiXinService;
import com.yanfan.zutai.util.HttpPostAndGetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公众号配置Controller
 *
 * @author ruoyi
 * @date 2023-04-11
 */
@RestController
@RequestMapping("/zutai/bWeiXin")
public class BWeiXinController extends BaseController {
    @Autowired
    private IBWeiXinService bWeiXinService;

    /**
     * 查询公众号配置列表
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bWeiXin:list')")
    @GetMapping("/list")
    @SysQueryData
    public TableDataInfo list(BWeiXin bWeiXin) {
        startPage();
        List<BWeiXin> list = bWeiXinService.selectBWeiXinList(bWeiXin);
        return getDataTable(list);
    }

    /**
     * 导出公众号配置列表
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bWeiXin:export')")
    @Log(title = "公众号配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @SysQueryData
    public void export(HttpServletResponse response, BWeiXin bWeiXin) {
        List<BWeiXin> list = bWeiXinService.selectBWeiXinList(bWeiXin);
        ExcelUtil<BWeiXin> util = new ExcelUtil<BWeiXin>(BWeiXin.class);
        util.exportExcel(response, list, "公众号配置数据");
    }

    /**
     * 获取公众号配置详细信息
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bWeiXin:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(bWeiXinService.selectBWeiXinById(id));
    }

    /**
     * 新增公众号配置
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bWeiXin:add')")
    @Log(title = "公众号配置", businessType = BusinessType.INSERT)
    @PostMapping
    @SysInitData
    public AjaxResult add(@RequestBody BWeiXin bWeiXin) {
        return toAjax(bWeiXinService.insertBWeiXin(bWeiXin));
    }

    /**
     * 修改公众号配置
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bWeiXin:edit')")
    @Log(title = "公众号配置", businessType = BusinessType.UPDATE)
    @PutMapping
    @SysInitUpdateData
    public AjaxResult edit(@RequestBody BWeiXin bWeiXin) {
        bWeiXinService.renovateToken();
        return AjaxResult.success();
    }

    /**
     * 删除公众号配置
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bWeiXin:remove')")
    @Log(title = "公众号配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bWeiXinService.deleteBWeiXinByIds(ids));
    }

    /**
     * 网站扫码绑定公众号
     */
    @Log(title = "扫码绑定公众号", businessType = BusinessType.INSERT)
    @PostMapping(value = "bindWeiXin")
    public AjaxResult bindWeiXin() {
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + bWeiXinService.getToken();
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapInfo = new HashMap<>();
        map.put("action_name", "QR_LIMIT_STR_SCENE");
        Map<String, Object> mapUserName = new HashMap<>();
        mapUserName.put("scene_str", SecurityUtils.getUsername() + "-" + SecurityUtils.getDeptId());
        mapInfo.put("scene", mapUserName);
        map.put("action_info", mapInfo);
        String res = HttpPostAndGetUtil.doPost(url, JSON.toJSONString(map), "", "");
        JSONObject jsonObject = JSONObject.parseObject(res, JSONObject.class);
        if (jsonObject.get("ticket") != null) {
            url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + jsonObject.get("ticket").toString();
            return AjaxResult.success(url);
        } else if (jsonObject.get("errcode") != null && Convert.toInt(jsonObject.get("errcode")) == 4001) {
            bWeiXinService.renovateToken();
            return AjaxResult.error("请求Token已过期，请重试");
        } else {
            return AjaxResult.error("请求超时，请重试");
        }
    }
}
